package com.hqj.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

/**
 * 属性类properties
 */
public class Test01 {

    public static void main(String[] args) {
        ProClass pc = new ProClass();

        Properties pro = pc.method();
        File f1 = pc.createProFile();

        pc.outPro(f1,pro);

        pro = pc.InPro(f1);
        //取值
        for(Object obj:pro.keySet()){
            String key = obj+"";
            String value = pro.getProperty(key);
            System.out.println("key:"+key+",value:"+value);
        }
    }

}
class ProClass{

    public Properties method(){
        Properties pro = new Properties();
        //赋值
        pro.setProperty("cn","中国");
        pro.setProperty("us","美国");
        pro.setProperty("us","美利坚");

        pro.containsKey("cn");

        //取值
        /*for(Object obj:pro.keySet()){
            String key = obj+"";
            String value = pro.getProperty(key);
            System.out.println("key:"+key+",value:"+value);
        }*/

        return pro;
    }

    public File createProFile(){
        File f = new File("E:\\Entor\\jsd202006\\frms");
        this.createDir(f);
        File f1 = new File(f,"test.properties");
        this.createFile(f1);
        return f1;
    }

    /**
     * 属性文件内容的写入
     * @param f
     * @param pro
     */
    public void outPro(File f,Properties pro){
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(f);

            //通过属性类，把属性内容写入的属性文件
            pro.store(fos,"首行注解");//comments:首行注解
            //关闭
            fos.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public Properties InPro(File f){

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(f);
            //创建属性对象
            Properties pro = new Properties();
            //加载内容
            pro.load(fis);
            //关闭
            fis.close();
            return  pro;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }






    public void createDir(File f){
        if(!f.exists()){
            f.mkdirs();
        }
    }

    public void createFile(File f){
        try {
            if(!f.exists()){
                f.createNewFile();
            }
        }catch (Exception e){
            System.out.println("文件创建失败，路径有误!"+e.getMessage());
        }
    }

}
